import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useImperativeHandle, useMemo, useRef, useState, useCallback, } from "react";
import { templateCloudDownload, templateImport, templateList } from "./service";
import { Popup, DataGrid, Button } from "devextreme-react";
import { DevPopup } from "~/public/cpas-ui";
import { Column } from "devextreme-react/data-grid";
import notify from "devextreme/ui/notify";
import { LoadPanel } from "devextreme-react/load-panel";
import DraftApi from "./DraftApi";
import { Modal, Progress } from "antd";
import Notify from "devextreme/ui/notify";
const CloudTemplatePopup = React.forwardRef((props, ref) => {
    const { cloudData, reloadTable } = props;
    const { cloudTempType, localTempTypeList } = cloudData;
    const [visible, setVisible] = useState(false);
    const [visibleCloud, setVisibleCloud] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [devTableData, setDevTableData] = useState([]);
    const [devTableCloudData, setDevTableCloudData] = useState([]);
    const devGridRef = useRef();
    const [selectData, setSelectData] = useState({});
    const [loadPanelVisible, setLoadPanelVisible] = useState(false);
    let importInterval = null;
    let exportInterval = null;
    const [processObj, setProcess] = useState({
        process: 0,
        message: "准备开始",
    });
    const popupRef = useRef();
    const getCloudTempleteList = async () => {
        setLoadPanelVisible(true);
        const res = await templateList({ tempType: cloudTempType });
        if (res.success) {
            setDevTableCloudData(res.data);
        }
        else {
            notify("获取云模板数据失败！", "error", 2000);
        }
        setLoadPanelVisible(false);
    };
    // 自定义方法
    useImperativeHandle(ref, () => ({
        showTemplate: () => {
            setVisibleCloud(true);
            getCloudTempleteList();
        },
    }));
    const onSelectionData = useCallback(({ selectedRowsData }) => {
        if (selectedRowsData[0]) {
            setSelectData(selectedRowsData[0]);
        }
    }, [selectData]);
    function startImportStatus() {
        importInterval = setInterval(async () => {
            const result = await DraftApi.getImportState();
            setProcess(result);
        }, 300);
    }
    function stopImportStatus() {
        clearInterval(importInterval);
        setProcess({
            process: 0,
            message: "准备开始",
        });
    }
    function startExportStatus() {
        exportInterval = setInterval(async () => {
            const result = await DraftApi.getExportState();
            setProcess(result);
        }, 300);
    }
    function stopExportStatus() {
        clearInterval(exportInterval);
        setProcess({
            process: 0,
            message: "准备开始",
        });
    }
    function Toast(msg, type) {
        if (!type) {
            type = "info";
        }
        Notify({
            message: `${msg}`,
            height: 45,
            width: 300,
            minWidth: 150,
            displayTime: 3500,
            type: type,
            position: "top center",
            animation: {
                show: {
                    type: "fade",
                    duration: 400,
                    from: 0,
                    to: 1,
                },
                hide: { type: "fade", duration: 40, to: 0 },
            },
        });
    }
    const fileDownload = async (filePath, P) => {
        if (cloudTempType === "底稿模板") {
            const path = filePath;
            const fileName = path.substring(path.lastIndexOf("\\") + 1);
            const r = await DraftApi.isExits(fileName);
            if (r.msg === "yes") {
                // 导入判断-----
                setLoadPanelVisible(false);
                popupRef.current.show({
                    title: "提示",
                    okCallback: async () => {
                        setLoadPanelVisible(true);
                        startImportStatus();
                        setIsLoading(true);
                        const mbTypeData = await DraftApi.import(path);
                        setProcess({
                            process: 100,
                            message: "完成",
                        });
                        setIsLoading(false);
                        stopImportStatus();
                        if (mbTypeData["code"] === 200) {
                            Toast("导入成功", "success");
                            setLoadPanelVisible(false);
                            closePopup();
                            if (reloadTable) {
                                reloadTable();
                            }
                        }
                        else {
                            setLoadPanelVisible(false);
                            Toast(mbTypeData["msg"], "error");
                        }
                    },
                });
            }
            else {
                startImportStatus();
                setIsLoading(true);
                const mbTypeData = await DraftApi.import(path);
                setProcess({
                    process: 100,
                    message: "完成",
                });
                setIsLoading(false);
                stopImportStatus();
                if (mbTypeData["code"] === 200) {
                    Toast("导入成功", "success");
                    setLoadPanelVisible(false);
                    closePopup();
                    if (reloadTable) {
                        reloadTable();
                    }
                }
                else {
                    setLoadPanelVisible(false);
                    Toast(mbTypeData["msg"], "error");
                }
            }
        }
        if (cloudTempType === "报告模板" || cloudTempType === "合并系统模板") {
            try {
                const resIm = await templateImport({
                    filePath: filePath,
                    TemplateType: cloudTempType === "报告模板" ? "报告系统模板" : cloudTempType,
                    TemplateFalg: "公共模板",
                    editUserName: P.editUserName,
                    editDate: P.editDate,
                    memo: P.memo,
                    reportType: P.reportType,
                });
                if (resIm.success) {
                    notify("下载成功,导入成功！", "success", 2000);
                    if (reloadTable) {
                        reloadTable();
                    }
                }
                else {
                    notify(`${resIm.msg}`, "error", 2000);
                }
                setLoadPanelVisible(false);
                closePopup();
            }
            catch (error) {
                setLoadPanelVisible(false);
                notify("导入失败！", "error", 2000);
            }
        }
    };
    const eventCloudDownload = async (P) => {
        setLoadPanelVisible(true);
        try {
            const res = await templateCloudDownload({
                tempType: cloudTempType,
                templateName: P.tempName,
                diskFileName: P.diskFileName,
            });
            if (res.success) {
                fileDownload(res.data, P);
            }
            else {
                notify("下载失败！", "error", 2000);
                setLoadPanelVisible(false);
            }
        }
        catch (error) {
            notify(`下载失败！${error}`, "error", 2000);
            setLoadPanelVisible(false);
        }
    };
    const closePopup = () => {
        setVisibleCloud(false);
        setDevTableCloudData([]);
        setSelectData({});
    };
    return (_jsx("div", { children: _jsxs(Popup, { ref: ref, title: "\u4E91\u6A21\u677F", dragOutsideBoundary: true, resizeEnabled: true, visible: visibleCloud, width: 750, height: 500, ...props, onHiding: () => {
                closePopup();
            }, children: [_jsxs("div", { style: {
                        display: "flex",
                        flexDirection: "row-reverse",
                        marginBottom: "8px",
                    }, children: [_jsx(LoadPanel, { shadingColor: "rgba(0,0,0,0.4)", visible: loadPanelVisible }), _jsx(Button, { type: "default", className: "defaultBtn", onClick: async () => {
                                if (!selectData.diskFileName) {
                                    return notify("请选择模板名称！", "warning", 2000);
                                }
                                else {
                                    let templist = localTempTypeList?.map((a) => {
                                        return a.tempName;
                                    });
                                    if (templist?.includes(selectData.tempName.replace(".rar", ""))) {
                                        popupRef.current.show({
                                            title: "提示",
                                            okText: "确定",
                                            okCallback: () => {
                                                eventCloudDownload(selectData);
                                            },
                                        });
                                    }
                                    else {
                                        eventCloudDownload(selectData);
                                    }
                                }
                            }, text: "\u4E0B\u8F7D" })] }), _jsx("div", { style: {
                        width: "100%",
                        height: "calc(100% - 50px)",
                    }, children: useMemo(() => {
                        return (_jsxs(DataGrid, { height: "100%", width: "100%", dataSource: devTableCloudData, keyExpr: "id", className: "PaperDevSortableGrid devHeadersCenter", ref: devGridRef, showBorders: true, showRowLines: true, showColumnLines: true, scrolling: { rowRenderingMode: "virtual" }, selection: {
                                mode: "single",
                            }, onSelectionChanged: onSelectionData, paging: {
                                enabled: false,
                            }, groupPanel: {
                                visible: false,
                            }, children: [_jsx(Column, { caption: "\u5E8F\u53F7", alignment: "center", width: 60, cellRender: (row) => {
                                        const { data, rowIndex } = row;
                                        return _jsx("div", { children: rowIndex + 1 });
                                    } }), _jsx(Column, { caption: "\u6A21\u677F\u540D\u79F0", dataField: "tempName", alignment: "left", dataType: "string" }), _jsx(Column, { width: 90, caption: "\u62A5\u544A\u7C7B\u578B", dataField: "reportType", alignment: "left", dataType: "string" }), _jsx(Column, { width: 90, caption: "\u53D1\u5E03\u4EBA", dataField: "editUserName", alignment: "left", dataType: "string" }), _jsx(Column, { caption: "\u53D1\u5E03\u65F6\u95F4", dataField: "editDate", alignment: "left", dataType: "string" }), _jsx(Column, { caption: "\u5907\u6CE8\u8BF4\u660E", dataField: "memo", alignment: "left", dataType: "string" })] }));
                    }, [devTableCloudData]) }), _jsx(DevPopup.Default, { ref: popupRef, children: () => {
                        return _jsx("span", { children: "\u8BE5\u6A21\u677F\u5DF2\u7ECF\u5B58\u5728,\u786E\u5B9A\u8986\u76D6\u8BE5\u6A21\u677F\u5417\uFF1F" });
                    } }), _jsxs(Modal, { visible: isLoading, closable: false, maskStyle: {
                        backgroundColor: "transparent",
                    }, footer: null, children: [_jsx(Progress, { percent: processObj.process }), _jsx("div", { style: { paddingTop: 10 }, children: processObj.message })] })] }) }));
});
export default CloudTemplatePopup;
